﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace BaiTu.Common
{
    /// <summary>
    /// 字符串扩展类
    /// </summary>
    public static class StringExtensions
    {
        /// <summary>
        /// 获取的字符串对应的byte的长度
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static int GetStringLength(this string str)
        {
            str.MustNotNull();

            return Encoding.Default.GetBytes(str).Length;
        }
        /// <summary>
        /// 判断字符串是否为Null Or Empty
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static bool IsNullOrEmpty(this string str)
        {
            return string.IsNullOrEmpty(str);
        }
        public static void IsNullOrEmptyThrowException(this string str, string errorMesage = null)
        {
            if (string.IsNullOrEmpty(str))
            {
                if (string.IsNullOrEmpty(errorMesage))
                {
                    throw new Framework.Exceptions.BaiTuCoreException("字符串为Null或Empty");
                }
                else
                {
                    throw new Framework.Exceptions.BaiTuCoreException(errorMesage);
                }
            }
        }
        /// <summary>
        /// 删除字符串尾部的回车/换行/空格
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static string RTrim(this string str)
        {
            return Helpers.StringHelper.RTrim(str);
        }
        /// <summary>
        /// 清除给定字符串中的回车及换行符
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static string ClearBR(this string str)
        {
            return Helpers.StringHelper.ClearBR(str);
        }
        /// <summary>
        /// 从字符串的指定位置截取制定长度的子字符串
        /// </summary>
        /// <returns></returns>
        public static string CutString(string str, int startIndex, int length)
        {
            str.IsNullOrEmptyThrowException();

            if (length < 0)
            {
                length = length * -1;
            }
            if (startIndex < 0)
            {
                startIndex = 0;
            }
            return str.Substring(startIndex, length);
        }
        /// <summary>
        /// 从字符串的指定位置开始截取到字符串结尾的了符串
        /// </summary>
        /// <param name="str"></param>
        /// <param name="startIndex"></param>
        /// <returns></returns>
        public static string CutString(string str, int startIndex)
        {
            str.IsNullOrEmptyThrowException();
            return CutString(str, startIndex, str.Length);
        }
    }
}
